<template>
  <div class="content">
    <div>新增订单管理</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="订单编号" prop="name" class="form-1">
        <el-input v-model="ruleForm.order_id" disabled></el-input>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="ruleForm.customer_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="contact_name">
        <el-select v-model="ruleForm.contact_name" placeholder="请选择联系人">
          <el-option
            v-for="(item, index) in contact"
            :label="item.contact_name"
            :value="item.contact_name"
            :key="index"
            @click.native="getId(item.contact_id)"
          ></el-option>
        </el-select>
        <el-button type="success" class="btn" @click="jumpAddContact"
          ><i class="el-icon-menu"></i>新增</el-button
        >
      </el-form-item>
      <el-form-item label="订单总金额">
        <el-input v-model="ruleForm.order_amount"></el-input>
        <i class="el-icon-question"></i>
        <span>自动结算</span>
      </el-form-item>
      <el-form-item label="已收款" prop="order_received">
        <el-input v-model="ruleForm.order_received"></el-input>
      </el-form-item>
      <el-form-item label="下单日期" required>
        <el-col :span="11">
          <el-form-item prop="order_date">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.order_date"
              style="width: 200px"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="交单日期">
        <el-col :span="11">
          <el-form-item prop="Submit_order_date">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.Submit_order_date"
              style="width: 200px"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="收货人">
        <el-input v-model="ruleForm.consignee"></el-input>
      </el-form-item>
      <el-form-item label="收货人电话">
        <el-input v-model="ruleForm.consignee_phone"></el-input>
      </el-form-item>
      <el-form-item label="收货人地址" class="form-1">
        <el-input
          v-model="ruleForm.consignee_address"
          class="receiveaddress"
        ></el-input>
      </el-form-item>
      <el-form-item label="附件" class="form-1">
        <el-upload
          class="upload-demo"
          action="http://192.168.221.217:8080//document/addDocument"
          name="fileList"
          :on-success="uploadSuccess"
          :on-error="uploadFail"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="备注" class="form-1">
        <el-input
          type="textarea"
          v-model="ruleForm.order_remark"
          class="remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 商品明细 -->
    <div class="goodsdetail">
      <span>商品明细</span>
      <Collect
        :tableData="tableData"
        :collect="collect"
        :money="money"
        class="money"
      />
      <el-button
        type="success"
        icon="el-icon-circle-plus"
        class="addGoods"
        @click="jumpAddPage"
        >新增商品</el-button
      >
    </div>
    <TabList
      :tableData="tableData"
      :btnList="btnList"
      :titleList="titleList"
      :linklist="linklist"
      :isCheck="isCheck"
      @DelorderGoods="getOrderGoods"
      @TableEdit="TableEdit"
    />
    <Page :total="totalSize" @getLimit="getLimit" @getPage="getPage" />
    <div class="employee">业务员:{{ ruleForm.employee_name }}</div>

    <div class="btnbox">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button @click="resetForm('ruleForm')">关闭</el-button>
    </div>
  </div>
</template>

<script>
import Collect from "../../components/collect.vue";
import Page from "../../components/Paging.vue";
import TabList from "../../components/OrderGoodsPage.vue";
import { mapActions } from "vuex";
// EditOrderGoodsAxios,
import { EditOrderAxios, getContactAxios } from "../../http/apis/orderApi";
// 时间戳的转换
import { timeFormat } from "../../utils/utils";
export default {
  name: "EditOrder",
  components: {
    Collect,
    TabList,
    Page,
  },
  data() {
    return {
      contact_id: "",
      currentPage: 1,
      pageSize: 3,
      totalSize: 0,
      order_id: "",
      isCheck: false,
      tableData: [],
      customer_id: "",
      btnList: [
        {
          id: 0,
          name: "删除",
          type: "订单商品",
        },
      ],
      titleList: [
        "index",
        "goods_name",
        "goods_cost",
        "goods_price",
        "order_goods_count",
        "discount",
        "order_amount",
        "goods_state",
        "order_goods_date",
      ],
      linklist: [
        {
          id: 0,
          name: "序号",
          isRouter: false,
        },
        {
          id: 1,
          name: "商品名称",
          isRouter: false,
        },
        {
          id: 2,
          name: "成本",
          isRouter: false,
        },
        {
          id: 3,
          name: "售价",
          isRouter: false,
        },
        {
          id: 4,
          name: "数量",
          isRouter: false,
        },
        {
          id: 5,
          name: "折扣",
          isRouter: false,
        },
        {
          id: 6,
          name: "总金额",
          isRouter: false,
        },
        {
          id: 7,
          name: "备注",
          isRouter: false,
        },
        {
          id: 8,
          name: "录入时间",
          isRouter: false,
        },
      ],
      // 金额
      collect: [
        // '汇总统计','总金额','已收款','欠款'
        { id: 2, name: "成本总和" },
        { id: 3, name: "售价总和" },
        { id: 4, name: "数量总和" },
        { id: 5, name: "折扣总和" },
        { id: 6, name: "最终总金额" },
      ],
      money: [],
      ruleForm: {
        order_date: "",
        Submit_order_date: "",
      },
      fileList: [],
      contact: [],
      rules: {
        order_received: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        contact_name: [
          { required: true, message: "请选择联系人", trigger: "change" },
        ],
        order_date: [
          {
            // type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        Submit_order_date: [
          {
            // type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        desc: [{ required: true, message: "请填写", trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapActions("orderStore", ["OrderGoodsInfoAction"]),
    // 上传成功的回调函数
    uploadSuccess(res) {
      console.log("成功：", res.data.fileList);
      this.fileList.push(res.data.fileList[0]);
    },
    // 上传失败的回调函数
    uploadFail(err) {
      console.log("失败：", err);
    },
    // 分页
    getLimit(val) {
      this.pageSize = val;
      console.log(this.pageSize);
      this.getOrderGoods();
      // this.money = [];
    },
    // 分页
    getPage(val) {
      this.currentPage = val;
      this.getOrderGoods();
      // this.money = [];
    },
    // 得到联系人id
    getId(id) {
      console.log("获取联系人id", id);
      this.contact_id = id;
    },

    // 点击跳转id
    jumpAddContact() {
      this.$router.push({
        path: "/order/cantactadd?state=editorder",
        query: { info: this.$route.query.editInfo },
      });
    },

    // 双击表格修改商品中的值
    TableEdit(row, column, cell, event) {
      this.orderid = row.orderid;
      this.order_goods_id = row.order_goods_id;
      // (this.order_goods_count = row.order_goods_count),
      // (this.discount = row.discount),
      // (this.order_goods_remark = row.order_goods_remark);
      console.log("row", row, "column", column, "cell", cell, "event", event);
      if (
        column.label != "管理" &&
        column.label != "序号" &&
        column.label != "商品名称" &&
        column.label != "成本" &&
        column.label != "售价"
      ) {
        event.target.innerHTML = "";
        //双击添加一个input框
        let cellInput = document.createElement("input");
        cellInput.value = "";
        //设置input框的类型，宽，padding，边框，圆角等都可以自己设置
        cellInput.setAttribute("type", "text");
        cellInput.style.width = "70%";
        cellInput.style.height = "90%";
        cellInput.style.padding = "5% 10%";
        cellInput.style.border = "1px solid #288EFE";
        cellInput.style.borderRadius = "3px";
        cell.appendChild(cellInput);
        //当鼠标失去焦点时，判断输入是否为空，不为空的话可以删除input
        cellInput.onblur = function () {
          if (cellInput.value == "") {
            alert("字段名不能为空");
            cellInput.style.border = "1px solid #FD1B1E";
          } else {
            cell.removeChild(cellInput);
            event.target.innerHTML = cellInput.value;
            console.log("event.target.innerHTML", event.target.innerHTML);
            this.order_goods_count = event.target.innerHTML;
            console.log("this.order_goods_count", this.order_goods_count);
            sessionStorage.setItem("count", this.order_goods_count);
          }
        };
      }
    },

    submitForm() {
      // 修改订单请求
      this.ruleForm = {
        order_amount: this.ruleForm.order_amount,
        order_date: timeFormat(this.ruleForm.order_date),
        consignee: this.ruleForm.consignee,
        consignee_address: this.ruleForm.consignee_address,
        consignee_phone: this.ruleForm.consignee_phone,
        order_received: this.ruleForm.order_received,
        Submit_order_date: timeFormat(this.ruleForm.Submit_order_date),
        order_remark: this.ruleForm.order_remark,
        contact_id: this.contact_id,
        order_id: this.ruleForm.order_id,
      };
      console.log("修改之后的数据", this.ruleForm);
      EditOrderAxios(this.ruleForm)
        .then((res) => {
          console.log("修改订单请求成功", res.data);
          this.$router.push({
            path: "/order/orderlist",
            query: { editinfo: this.info },
          });
        })
        .catch((err) => {
          console.log("修改订单请求错误", err);
        });

      //   this.order_goods_count = sessionStorage.getItem("count");
      //   console.log("this.order_goods_count", this.order_goods_count);
      //   // 修改商品信息
      //   console.log(
      //     "order_goods_id",
      //     this.order_goods_id,
      //     "orderid",
      //     this.orderid,
      //     "order_goods_count",
      //     this.order_goods_count,
      //     "discount",
      //     this.discount,
      //     "order_goods_remark",
      //     this.order_goods_remark
      //   );
      //   EditOrderGoodsAxios({
      //     order_goods_id: this.order_goods_id,
      //     order_id: this.orderid,
      //     order_goods_count: this.order_goods_count,
      //     discount: this.discount,
      //     order_goods_remark: this.order_goods_remark,
      //   })
      //     .then((res) => {
      //       console.log("修改订单商品信息请求成功", res.data);
      //       this.$router.push({
      //         path: "/order/orderlist",
      //         query: { info: this.info },
      //       });
      //     })
      //     .catch((err) => {
      //       console.log("修改订单商品信息请求错误", err);
      //     });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },

    // 显示金额数据
    compute() {
      this.money = [];
      var goods_cost = 0;
      var goods_price = 0;
      var order_goods_count = 0;
      var discount = 0;
      var order_amount = 0;
      console.log("tableData", this.tableData);
      for (var a = 0; a < this.tableData.length; a++) {
        goods_cost += this.tableData[a].goods_cost;
        goods_price += this.tableData[a].goods_price;
        order_goods_count += this.tableData[a].order_goods_count;
        discount += this.tableData[a].discount;
        order_amount += this.tableData[a].order_amount;
      }
      this.money.push(goods_cost);
      this.money.push(goods_price);
      this.money.push(order_goods_count);
      this.money.push(discount);
      this.money.push(order_amount);
      console.log("money", this.money);
    },
    // 点击新增按钮跳转页面
    jumpAddPage() {
      this.$router.push({
        path: "/order/OrderAdd?state=editorder",
        query: { info: this.$route.query.editInfo },
      });
    },

    // 获取商品详情
    getOrderGoods() {
      this.tableData = [];
      this.OrderGoodsInfoAction({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        orderId: this.order_id,
      })
        .then((res) => {
          console.log("获取订单商品详情数据请求成功", res.data.data);
          let arr = res.data.data[1];
          this.totalSize = res.data.data[0];
          let index = 1;
          arr.forEach((item) => {
            let obj = {
              index: index++,
              goods_name: item.goods_name,
              goods_cost: item.goods_cost,
              goods_price: item.goods_price,
              order_goods_count: item.order_goods_count,
              discount: item.discount,
              order_amount:
                item.goods_price * item.order_goods_count - item.discount,
              goods_state: item.goods_state,
              order_goods_date: timeFormat(item.order_goods_date),
              orderid: item.orderid,
              order_goods_id: item.order_goods_id,
            };
            this.tableData.push(obj);
          });
          console.log(this.tableData);
          // 计算
          this.compute();
        })
        .catch((err) => {
          console.log("获取订单商品详情数据请求成功错误", err);
        });
    },
  },

  created() {
    // 显示数据在表单里
    console.log(this.$route.query.editInfo || this.$route.query.info);
    const Info = this.$route.query.editInfo || this.$route.query.info;
    this.order_id = Info.order_id;

    console.log("获取客户数据", Info);
    console.log("获取订单id", this.order_id);
    this.customer_id = Info.customer_Id;
    console.log("客户ID", this.customer_id);

    // 获取联系人
    getContactAxios(this.customer_id)
      .then((res) => {
        console.log("获取联系人请求成功", res.data.data);
        this.contact = res.data.data;
      })
      .catch((err) => {
        console.log("获取联系人请求错误", err);
      });
    let obj = {
      order_id: Info.order_id,
      customer_name: Info.customer_name,
      contact_name: Info.contact_name,
      order_amount: Info.order_amount,
      order_received: Info.order_received,
      order_date: Info.order_date,
      Submit_order_date: Info.Submit_order_date,
      consignee: Info.consignee,
      consignee_phone: Info.consignee_phone,
      consignee_address: Info.consignee_address,
      order_remark: Info.order_remark,
      employee_name: Info.employee_name,
    };
    // 显示数据在说表单中
    this.ruleForm = obj;
    this.getOrderGoods();
  },
};
</script>

<style lang="scss" scoped>
form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
  margin-top: 20px;
}
.el-form-item {
  width: 500px;
}
.form-1 {
  width: 90%;
}
.el-input {
  width: 200px;
}
.receiveaddress {
  width: 500px;
}
.remark {
  width: 100%;
}
// 修改商品
.goodsdetail {
  width: 100%;
  position: relative;
}

.goodsdetail span {
  float: left;
  line-height: 55px;
  margin-left: 10px;
}

.money {
  width: 100%;
}
.addGoods {
  position: absolute;
  right: 10px;
  top: 5px;
}

.btn {
  margin-left: 10px;
  box-sizing: border-box;
}
.el-col {
  overflow: initial;
}
.employee {
  margin: 20px;
}
.btnbox {
  width: 160px;
  margin: 20px auto;
}
</style>